﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using CourseSystem.Core.BLL;

namespace CourseSystem.Common
{
    public class RandomStr
    {
        public static Dictionary<string, DateTime> RandomDic;
        private static object _synLock = new object();
        private static bool _isRunning = false;

        static RandomStr()
        {
            RandomDic = new Dictionary<string, DateTime>();
        }

        private static bool Insert(string str)
        {
            Clear();
            if (RandomDic.ContainsKey(str))
                return false;
            RandomDic.Add(str, DateTime.Now);
            return true;
        }

        public static void Clear()
        {
            if (!_isRunning)
                lock (_synLock)
                    if (!_isRunning)
                    {
                        _isRunning = true;
                        var now = DateTime.Now;
                        foreach (KeyValuePair<string, DateTime> item in RandomDic)
                        {
                            if (item.Value.AddHours(1) < now)
                            {
                                AttachmentsBLL.DelFileByRanStr(item.Key);
                            }
                        }
                    }
        }

        public static bool Remove(string str)
        {
            Clear();
            return RandomDic.Remove(str);
        }

        public static bool Check(string str)
        {
            if (string.IsNullOrEmpty(str))
                return false;
            if (!RandomDic.ContainsKey(str))
                return false;
            RandomDic[str] = DateTime.Now;
            return true;
        }

        private static string GetByTime()
        {
            return DateTime.Now.ToString("mmddHHmmssfff");
        }

        public static string GetByTime(string perfix)
        {
            var re = string.IsNullOrEmpty(perfix) ? GetByTime() : perfix + GetByTime();
            if (Insert(re))
                return re;
            return "";
        }
    }
}
